from rest_framework import serializers
from .models import WallPost, WallComment, PostLike
from apps.users.serializers import UserSerializer

class WallCommentSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = WallComment
        fields = ['id', 'post', 'user', 'content', 'created_at', 'username']

class WallPostSerializer(serializers.ModelSerializer):
    user_info = UserSerializer(source='user', read_only=True)
    comments = WallCommentSerializer(many=True, read_only=True)
    liked = serializers.SerializerMethodField()

    class Meta:
        model = WallPost
        fields = [
            'id', 
            'content', 
            'created_at',
            'user',
            'user_info',
            'comments',
            'tags',
            'duration',
            'score',
            'likes_count',
            'comments_count',
            'liked',
            'image'
        ]
        read_only_fields = ['likes_count', 'comments_count', 'liked']

    def get_liked(self, obj):
        request = self.context.get('request')
        user_id = request.query_params.get('user_id') if request else None
        if user_id:
            return obj.likes.filter(user_id=user_id).exists()
        return False

    def create(self, validated_data):
        # 确保 tags 是列表
        if 'tags' not in validated_data:
            validated_data['tags'] = []
        return super().create(validated_data)

class PostLikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostLike
        fields = ['id', 'post', 'user', 'created_at'] 